package com.itheima.util;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.ResourceBundle;

public class JedisUtil {
    /*private static int maxTotal;
    private static int maxWaitMillis;
    private static int maxIdle;
    private static String host;
    private static int port;*/
    private static JedisPool pool;
    static {
        //1.读取配置参数 只读取一次：【类加载器】 【ResourceBundle】
        /*InputStream inputStream = JedisUtil.class.getClassLoader().getResourceAsStream("jedis.properties");
        Properties p = new Properties();
        p.load(inputStream);
        String maxTotal = p.getProperty("jedis.maxTotal");*/
        //【ResourceBundle】 jedis.properties
        //注意这里只需要书写配置文件名jedis即可
        ResourceBundle bundle = ResourceBundle.getBundle("jedis");
        //根据key获取value
        int maxTotal = Integer.parseInt(bundle.getString("jedis.maxTotal"));
        int maxWaitMillis = Integer.parseInt(bundle.getString("jedis.maxWaitMillis"));
        int maxIdle = Integer.parseInt(bundle.getString("jedis.maxIdle"));
        String host = bundle.getString("jedis.host");
        int port = Integer.parseInt(bundle.getString("jedis.port"));

        //2.创建连接池：提前创建，只创建一次
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(maxTotal);
        config.setMaxWaitMillis(maxWaitMillis);
        config.setMaxIdle(maxIdle);

        pool = new JedisPool(config,host,port);
    }
    //3.提供连接池
    public static JedisPool getJedisPool(){
        return pool;
    }
    //4.提供方法从连接池中获取连接对象
    public static Jedis getJedis(){
        return pool.getResource();
    }
    //5.释放连接
    public static void closeJedis(Jedis jedis){
        if(jedis != null){
            jedis.close();
        }
    }
}
